package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishDto;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish>
        implements DishService{
    @Autowired
    private DishFlavorService dishFlavorService;

    @Transactional
    @Override
    public void saveWithFlavor(DishDto dish) {
        // 完成多表操作
        // 1.把菜品的基本信息，保存到菜品表
        // dishDto这个对象本身继承Dish,所有这个对象里面肯定有菜品的基本信息
        this.save(dish);
        // 2.把口味列表的数据，批量的保存到菜品口味表中，这里注意，保存菜品口味的时候，一定要注意关联
        // 保存菜品口味的时候，必须设置对应的菜品的id dishId
        List<DishFlavor> flavorList = dish.getFlavors();
        for (DishFlavor dishFlavor:flavorList){
            // 把上一步，菜品的Id ,赋值给菜品口味的菜品ID
            dishFlavor.setDishId(dish.getId());
        }
        // 使用Lamda语法变量
        flavorList.stream().forEach(
                (item)->item.setDishId(dish.getId())
        );
        // 菜品口味表的操作是肯定使用菜品口味的Service
        dishFlavorService.saveBatch(flavorList);
    }

    @Override
    public DishDto getByIdwithFlavor(long id) {
        //1.查询菜品基本信息
        Dish dish = this.getById(id);
        // 我们的返回值是DishDto,所有我们需要把原始的dish对象，复制到dishDto
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish,dishDto);
        //2.查询菜品口味列表,一定要想到用什么SQL语句查询，条件是什么
        // where dish_id = 1605826500458749954
        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(DishFlavor::getDishId,dish.getId());
        List<DishFlavor> dishFlavorList = dishFlavorService.list(queryWrapper);
        // 获取到菜品口味列表后，赋值给dishDto
        dishDto.setFlavors(dishFlavorList);
        return dishDto;
    }

    @Transactional//设计多表，一定加事务
    @Override
    public void updateWithFlavor(DishDto dishDto) {
        //更新菜品基本表
        this.updateById(dishDto);
        // 更新菜品口味表,口味表如何更新？
        // 开发中，通常的做法：先删除旧的数据，再添加新的数据
        // 删除是根据条件删除 delete from dish_flavor where dish_id = 1605826500458749954;
        LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(DishFlavor::getDishId,dishDto.getId());
        dishFlavorService.remove(lambdaQueryWrapper);
        //批量添加
        dishDto.getFlavors().stream().forEach((dishFlavor)->dishFlavor.setDishId(dishDto.getId()));
        dishFlavorService.saveBatch(dishDto.getFlavors());
    }
}
